package cn.mjnxin.iot.connector.connector;

import java.util.concurrent.TimeUnit;

import cn.mjnxin.iot.base.util.CommonUtil;
import cn.mjnxin.iot.transfer.ConnectionWacthDog;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * 前置作为客户端连网关
 * 
 * @author CLG 2023年10月10日
 * @version V1.0.0
 */
public class ConnectorAsClient2Gate {
    private EventLoopGroup           worker             = new NioEventLoopGroup();
    private final ConnectionWacthDog connectionWacthDog;
    private final Bootstrap          bootstrap;

    public ConnectorAsClient2Gate(ConnectionWacthDog connectionWacthDog, String gateAddress, Integer gatePort) {
        this.connectionWacthDog = connectionWacthDog;
        this.bootstrap = connectionWacthDog.getBootstrap();
    }
    
    public void config(int timeout) {
        bootstrap.group(worker).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
//			.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 500)
            .option(ChannelOption.SO_SNDBUF, 32 * 1024)
            .option(ChannelOption.SO_RCVBUF, 32 * 1024) 
			.option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT)
//			.localAddress(gateAddr, gatePort)
            // 这里方法名与服务端不一样，其他一致
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                	// 这里的IdleStateHandler仅仅是打印网络连接空闲信息，timeout分钟
					sc.pipeline().addLast(new IdleStateHandler(0, 0, timeout, TimeUnit.MINUTES));
					sc.pipeline().addLast(connectionWacthDog.getChannelHandlers());
                }
            }
        );
        
    	connectionWacthDog.doConnect();
    }

    public String getLocalAddress() {
    	return connectionWacthDog.getLocalAddress();
    }
    
    /**
     * 关闭服务
     */
    public void close() {
        CommonUtil.closeEventLoop(worker);
        worker.shutdownGracefully();
    }
}
